package com.yx.pc.api.controller;

import com.yx.common.annotation.Log;
import com.yx.common.utils.PageUtils;
import com.yx.common.utils.Query;
import com.yx.common.utils.R;
import com.yx.modules.api.annotation.LoginUser;
import com.yx.modules.api.entity.TbUser;
import com.yx.pc.api.service.*;
import com.yx.system.dao.TdOnlinePayLogMapper;
import com.yx.system.entity.*;
import com.yx.system.service.TbRationService;
import com.yx.utils.*;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/pc/api/order")
public class PcTdOrderController {

    @Autowired
    private PcTdOrderService tdOrderService;

    @Autowired
    private PcTdSectionService tdSectionService;

    @Autowired
    private PcTdBookService tdBookService;

    @Autowired
    private TdOnlinePayLogMapper tdOnlinePayLogMapper;
    @Autowired
    private PcTdWalletPayLogService tdWalletPayLogService;
    @Autowired
    private PcTbUserService tbUserService;
    @Autowired
    private TbRationService tbRationService;

    /**
     * 按ID查询订单
     *
     * @return
     */
    @Log
    @PostMapping("findByUid")
    public R findByUId(int id) {
        return R.ok().put("user", tdOrderService.selectByPrimaryKey(id));
    }

    /**
     * 新增或修改
     *
     * @return
     */
    @Log
    @PostMapping("saveOrUpdate")
    public R saveOrUpdate(TdOrder tdOrder) {
        if (tdOrder.getId() == 0 || tdOrder.getId() == null) {
            tdOrderService.insert(tdOrder);
        } else {
            tdOrderService.updateByPrimaryKey(tdOrder);
        }
        return R.ok();
    }

    /**
     * 删除 (软删除)
     *
     * @return
     */
    @Log
    @PostMapping("delete")
    public R delete(int id) {
        tdOrderService.deleteByPrimaryKey(id);
        return R.ok();
    }

    /**
     * 创建订单并且购买
     *
     * @param tbUser
     * @param sectionid 章节ID
     * @return
     */
    @PostMapping("orderCreate")
    public R orderCreate(@LoginUser TbUser tbUser, String sectionid,Integer bookid) {
        JSONArray ja = JSONArray.fromObject(sectionid);

        int totalMoney = 0;
        long a = System.currentTimeMillis();
        Map<String, Object> map = new HashMap<>();
        map.put("orderStatus", PayStatus.success.getName());
        map.put("uuid", tbUser.getUuid());
        map.put("bookid", bookid);
        map.put("grop","1");
        List<TdOrder> tdOrderList = tdOrderService.queryList(map);
        for (int i = 0; i < tdOrderList.size(); i++) {
            for (int j = 0; j <ja.size() ; j++) {
                if (tdOrderList.get(i).getSectionid() == Integer.parseInt(ja.get(j).toString())){
                    ja.remove(tdOrderList.get(i).getSectionid());
                }
            }

        }
        Integer[] Ids = new Integer[ja.size()];
        for (int i = 0; i < ja.size(); i++) {
            Ids[i] = Integer.parseInt(ja.get(i).toString());
        }
        List<TdSection> tdSectionList = tdSectionService.findByArrIds(Ids);
        List<TdSection> tdSections = new ArrayList<>(tdSectionList);
        for (TdSection tdSection:tdSectionList){
            if (tdSection.getTotalfee()==0){
                tdSections.remove(tdSection);
            }
            totalMoney += tdSection.getTotalfee();
        }
        long b = System.currentTimeMillis();
        System.out.println("======================================执行时间"+(b-a)+"=================================================");
        if (tbUser.getBalance() < totalMoney) {
            return R.error("用户余额不足！").put("price",(totalMoney-tbUser.getBalance()));
        }

        Thread thread = new Thread(){
            public void run(){
                tdOrderService.buySections(bookid,tdSections,tbUser);
            }
        };

        thread.start();
        if (ja.size()>1){
            return R.ok("购买全书需要一定时间，如果章节提醒重新购买，请勿重复购买，稍微等待后刷新页面重试");
        }else {
            return R.ok("购买成功");
        }

    }

    /**
     * 查询用户已经购买章节
     *
     * @param id bookid
     * @return
     */
    @PostMapping("pay")
    public R pay(@LoginUser TbUser tbUser, Integer id) {
        TdBook tdBook = tdBookService.selectByPrimaryKey(id);
        Map<String, Object> map = new HashMap<>();
        map.put("bookUUID", tdBook.getId());
        List<TdSection> tdSectionList2 = new ArrayList<>();
        List<TdSection> tdSectionList = tdSectionService.queryList(map);
        for (int i = 0; i < tdSectionList.size(); i++) {
            map.put("orderStatus", PayStatus.success.getName());
            map.put("uuid", tbUser.getUuid());
            map.put("sectionid", tdSectionList.get(i).getId());
            if (tdOrderService.queryList(map).size() > 0) {
                tdSectionList2.add(tdSectionList.get(i));
            }
        }
        return R.ok().put("tdSection", tdSectionList2);
    }

    /**
     * 查询单条订单的详情信息
     *
     * @param id 订单ID
     * @return
     */
    @PostMapping("find")
    public R find(@LoginUser TbUser tbUser, Integer id) {
        TdOrder order = tdOrderService.selectByPrimaryKey(id);
        return R.ok().put("order", order);
    }

    /**
     * 获取我的订单列表
     *
     * @return
     */
    @PostMapping("list")
    public R getOrderList(@LoginUser TbUser tbUser, @RequestParam Map<String, Object> map) {
        List<TdOrder> orderList = null;
        map.put("uuid", tbUser.getUuid());
        Query query = new Query(map);
        orderList = tdOrderService.queryList(query);
        int total = tdOrderService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());
        return R.ok().put("orderList", pageUtil);
    }

    /**
     * 删除我的订单
     *
     * @param id 订单ID
     * @return
     */
    @PostMapping("del")
    public R delOrder(@LoginUser TbUser tbUser, int id) {
        return R.ok().put("order", tdOrderService.selectByPrimaryKey(id));
    }

//    public static void main(String[] args){
//        String arr = "['36','37','38']";
//        JSONArray ja = JSONArray.fromObject(arr);
//        for (int i = 0;i<ja.size();i++){
//            System.out.println(ja.get(i));
//        }
//    }
}
